"""
    Partner Gate application 
    saves MD5 urls into datastore
    checks if MD5 url has already been
    accessed within a 7 day period
"""

from flask import Flask, current_app
from admin import admin
from url import pgate
from converters import md5Converter
from models import db


def create_app():
    """Factory function to create the pgate flask application."""
    app = Flask(__name__)
    app.config.from_pyfile('gate.cfg')
    db.init_app(app)

    # add converter for url matching for md5
    app.url_map.converters['md5'] = md5Converter

    # add 500/404 error handler
    app.error_handler_spec[None][500] = default_error_handler
    app.error_handler_spec[None][404] = page_not_found

    # add file logger
    import logging
    from logging.handlers import TimedRotatingFileHandler
    file_handler = TimedRotatingFileHandler(app.config['TRACE_FILE'],
                                            'midnight', 1)
    # might be able to move this out to logging.conf
    fmt = logging.Formatter('%(asctime)-15s %(name)s:%(levelname)s %(module)s:%(lineno)d:  %(message)s')
    file_handler.setFormatter(fmt)
    app.logger.addHandler(file_handler)

    # register the blueprints
    app.register_blueprint(pgate) 
    app.register_blueprint(admin)
    return app    

def page_not_found(error):
    """Returns the default value "0", 200 OK when a url would normally
       come back as a HTTP 404 error

       Examples:
         1. http://pglb.buzzfed.com/-0005/bogus-looking-url => 0, 200 OK"""
    return "0", 200

def default_error_handler(error):
    """Returns the default value "0", 200 OK when a url would normally
       come back as a HTTP 500 error. """
    current_app.logger.error(error)
    return "0", 200

if __name__ == "__main__":
    app = create_app()
    app.run()